module rdma_engine #(
  parameter NODE_ID = 0,
  parameter TOTAL_NODES = 4
)(
  input  wire         clk,
  input  wire         rst_n,
  
  // 本地内存接口
  input  wire [31:0]  local_addr,
  input  wire [127:0] local_data,
  output wire [127:0] remote_data,
  
  // 物理层接口
  input  wire         phy_rx_valid,
  input  wire [63:0]  phy_rx_data,
  output wire         phy_tx_valid,
  output wire [63:0]  phy_tx_data
);

  // 数据包格式定义
  typedef struct packed {
    logic [7:0]  dest_id;
    logic [23:0] remote_addr;
    logic [31:0] data_0;
    logic [31:0] data_1;
  } rdma_packet_t;

  // 接收状态机
  enum {IDLE, RECV_HEADER, RECV_PAYLOAD} rx_state;
  rdma_packet_t rx_packet;
  
  always @(posedge clk) begin
    if (!rst_n) begin
      rx_state <= IDLE;
    end else case(rx_state)
      IDLE: 
        if (phy_rx_valid) begin
          rx_packet <= phy_rx_data;
          rx_state <= (phy_rx_data[63:56] == NODE_ID) ? RECV_PAYLOAD : IDLE;
        end
      RECV_PAYLOAD:
        if (phy_rx_valid) begin
          // 写入本地内存
          memory[rx_packet.remote_addr] <= {phy_rx_data, rx_packet.data_1};
          rx_state <= IDLE;
        end
    endcase
  end

  // 发送逻辑
  task automatic send_rdma(
    input [7:0]  dest,
    input [23:0] addr,
    input [63:0] data
  );
    phy_tx_data <= {dest, addr[23:0], data[63:32]};
    @(posedge clk);
    phy_tx_data <= data[31:0];
    phy_tx_valid <= 1;
  endtask

endmodule